#ifndef __LV_DISPLAY_H__
#define __LV_DISPLAY_H__

#include "PayBox.h"
#include <lvgl.h>

extern TFT_eSPI tft;

// LVGL空间
static lv_disp_draw_buf_t draw_buf;
static lv_color_t color_buf[TFT_HEIGHT * 10];

static void inline initLvKeys() {
  pinMode(PAY_KEY_ADD, INPUT_PULLUP);
  pinMode(PAY_KEY_MINUS, INPUT_PULLUP);
  pinMode(PAY_KEY_REFRESH, INPUT_PULLUP);
}

void setupLvDisplay() {
  initLvKeys();
  // 初始化LVGL Buffer
  lv_disp_draw_buf_init(&draw_buf, color_buf, NULL, TFT_HEIGHT * 10);

  /*Initialize the display*/
  static lv_disp_drv_t disp_drv;
  lv_disp_drv_init(&disp_drv);
  /*Change the following line to your display resolution*/
  disp_drv.hor_res = TFT_HEIGHT;
  disp_drv.ver_res = TFT_WIDTH;
  disp_drv.flush_cb = [](lv_disp_drv_t *disp, const lv_area_t *area,
                         lv_color_t *color_p) {
    uint32_t w = (area->x2 - area->x1 + 1);
    uint32_t h = (area->y2 - area->y1 + 1);

    tft.startWrite();
    tft.setAddrWindow(area->x1, area->y1, w, h);
    tft.pushColors((uint16_t *)&color_p->full, w * h, true);
    tft.endWrite();

    lv_disp_flush_ready(disp);
  };
  disp_drv.draw_buf = &draw_buf;
  lv_disp_drv_register(&disp_drv);

  /*Initialize the (dummy) input device driver*/
  static lv_indev_drv_t indev_drv;
  lv_indev_drv_init(&indev_drv);
  indev_drv.type = LV_INDEV_TYPE_KEYPAD;
  indev_drv.read_cb = [](lv_indev_drv_t *indev_driver, lv_indev_data_t *data) {
    if (digitalRead(PAY_KEY_ADD) == LOW) {
      data->key = LV_KEY_LEFT;
      data->state = LV_INDEV_STATE_PR;
    } else if (digitalRead(PAY_KEY_MINUS) == LOW) {
      data->key = LV_KEY_RIGHT;
      data->state = LV_INDEV_STATE_PR;
    } else if (digitalRead(PAY_KEY_REFRESH) == LOW) {
      data->key = LV_KEY_ENTER;
      data->state = LV_INDEV_STATE_PR;
    } else {
      data->state = LV_INDEV_STATE_REL;
    }
  };
  lv_indev_drv_register(&indev_drv);
}

#endif